#include <Arduino.h>  // 必须包含 Arduino 核心头文件
#include <Wire.h>

// 前向声明
void scanI2CDevices();
void checkCommonIssues();

// I2C 配置
#define I2C_SDA 21
#define I2C_SCL 22
#define I2C_FREQ 100000

void setup() {
  Serial.begin(115200);
  Wire.begin(I2C_SDA, I2C_SCL, I2C_FREQ);
  delay(2000);
  Serial.println("\nStarting I2C Scanner...");
}

void loop() {
  scanI2CDevices();
  delay(5000);
}

void scanI2CDevices() {
  int foundCount = 0;
  uint8_t error;  // 使用标准C类型替代byte

  Serial.println("Scanning I2C bus...");
  
  // 正确声明循环变量
  for (uint8_t address = 0x08; address < 0x78; address++) {
    Wire.beginTransmission(address);
    error = Wire.endTransmission();

    if (error == 0) {
      Serial.printf("Found device at 0x%02X", address);
      if (address == 0x40) {
        Serial.print(" (PCA9685 DEFAULT)");
      } else if (address >= 0x40 && address <= 0x7F) {
        Serial.print(" (Possible PCA9685)");
      }
      Serial.println();
      foundCount++;
    }
  }

  if (foundCount == 0) {
    checkCommonIssues();
  }
}

void checkCommonIssues() {
  Serial.println("\nTroubleshooting Tips:");
  Serial.println("1. Check I2C connections (SDA/SCL)");
  Serial.println("2. Verify PCA9685 power supply (5V)");
  Serial.println("3. Confirm address pins configuration");
}